package com.ait.edu.listener;

import com.ait.commonutils.exceptionHandler.GuilException;
import com.ait.edu.entity.Subject;
import com.ait.edu.entity.excel.SubjectData;
import com.ait.edu.service.SubjectService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class SuobjectExcelListener  extends AnalysisEventListener<SubjectData>{
// 有个很重要的点 DemoDataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
    public SubjectService subjectService;

    public SuobjectExcelListener() {
    }
    //如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
    public SuobjectExcelListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        System.out.println("subjectData-->"+subjectData);
            if (subjectData == null){
                throw new GuilException(405,"文件为空");
            }
            //判断一级
            Subject existOneSubject = existOneSubject(subjectData.getOneSubjectName());
            if (existOneSubject == null){
                existOneSubject = new Subject();
                existOneSubject.setParentId("0");
                existOneSubject.setTitle(subjectData.getOneSubjectName());
                subjectService.save(existOneSubject);
            }
            String pid = existOneSubject.getId();
            //判断二级
            Subject existTwoSubject = this.existTwoSubject(subjectData.getTwoSubjectName(), pid);

            if(existTwoSubject == null){
                existTwoSubject = new Subject();
                existTwoSubject.setParentId(pid);
                existTwoSubject.setTitle(subjectData.getTwoSubjectName());
                subjectService.save(existTwoSubject);
            }
    }

    //判断一级容器是否有重复的
    public Subject  existOneSubject(String name){
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");

       return subjectService.getOne(wrapper);


    }
    //判断二级容器是否有重复的
    public Subject  existTwoSubject(String name,String pid){
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);

        return subjectService.getOne(wrapper);


    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
